<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Repository\OrderCheckpointRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\RoadRescueOrderRepository;

use Log;
use Modules\Shop\Service\OrderRepairService;
//use Modules\Admin\Service\OrderRepairstoreService;
use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\ActivityRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\ActivityPushRepository;
use Modules\Admin\Service\OrderService;
use HiCommon\Repository\LogRepository;
use HiCommon\Service\JpushService;
use HiCommon\Repository\CouponGrantDetailRepository;
use Modules\Shop\Service\StoreOrderService;

class AutoScheduleService extends BaseService
{

    /**
     * 年检预约单-未支付30分钟后自动取消订单
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_auto_cancle_appointment()
    {
        //查询所有可用自动取消的订单
        $arr_field = ['id', 'shop_id', 'appointment_date', 'appointment_times', 'appointment_time_type', 'appointment_num', 'created_at'];
        $result = OrderCheckpointRepository::all_auto_cancel_order($arr_field)->toarray();
        if (!empty($result)) {
            foreach ($result as $value) {
                //取消订单
                $res = OrderCheckpointService::api_auto_cancle_appointment($value);
                if ($res['state'] != 0) {
                    return $res;
                }
            }
        }
        return hello_success('取消成功');
    }


    /**
     * 年检预约单-评价所有7天未评价订单-不给评分只标记订单为已评价状态
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_auto_apprise_appointment_order()
    {
        //查询所有7天未评价订单
        $result = OrderCheckpointRepository::apprise_all_waiting_appointment_order();
        if ($result === false) {
            return hello_error('评价失败');
        }
        return hello_success('评价成功');
    }

    /**********************************************服务订单定时处理*************************************************/

    /**
     * 服务订单-未支付30分钟后自动取消订单
     * @return array
     */
    public function api_auto_cancle_repair()
    {
        //查询所有可用自动取消的订单
        $arr_field = ['id', 'order_type'];
        $result = OrderRepairstoreRepository::all_auto_cancel_order($arr_field)->toarray();

        if (!empty($result)) {
            foreach ($result as $value) {
                //取消订单
                $res = OrderRepairService::api_auto_cancle_repair($value);
                if ($res['state'] != 0) {
                    return $res;
                }
            }
        }
        return hello_success('取消成功');
    }

    /**
     * 维修服务订单如已经支付但七天没去处理，定时任务自动退款
     * @return array
     */
    public function api_auto_repair_refund()
    {
        //查询所有可退款的订单
        /* $arr_field = ['id'];
         $result = OrderRepairstoreRepository::api_auto_repair_refund($arr_field)->toarray();

         if (!empty($result)) {
             foreach ($result as $value) {
                 //退款订单
                 return OrderRepairstoreService::refund($value['id'], '系统自动退款');
             }
         }*/
        return hello_success('没有待自动退款订单');
    }

    /**
     * 维修保养商户端确认完成后三天后，更新订单为用户确认已完成
     * @return array
     */
    public function confirm_order_repair()
    {
        $result = OrderRepairstoreRepository::all_confirm_order_repair();
        if (!empty($result)) {
            $orderIds = array_column($result, 'id');
            $up_data = ['is_finish' => 1, 'status' => 4];
            $res = OrderRepairstoreRepository::update_by_where_in($orderIds, $up_data);
            if ($res) {
                return hello_success('成功');
            } else {
                return hello_error('失败');
            }
        }
        return hello_success('成功');
    }

    /**********************************************积分商城订单定时处理*************************************************/
    /**
     * 积分订单-未支付30分钟后自动取消订单
     *
     * @return array
     * @author yang
     */
    public function api_auto_cancle_mall()
    {
        //查询所有可用自动取消的订单
        $arr_field = ['id'];
        $result = OrderMallRepository::all_auto_cancel_order($arr_field)->toarray();

        if (!empty($result)) {
            $res = '';
            foreach ($result as $value) {
                //取消订单
                OrderService::cancelOrder((int)$value['id']);
            }
            if ($res) {
                return hello_success('取消成功');
            } else {
                return hello_error('取消失败');
            }
        }
        return hello_success('暂无可取消订单');
    }

    /**********************************************商城普通订单定时处理*************************************************/
    /**
     * 普通订单-未支付30分钟后自动取消订单
     * @return array
     */
    public function api_auto_cancle_store()
    {
        //查询所有可用自动取消的订单
        $arr_field = ['id', 'user_coupons_id'];
        $result = StoreOrderRepository::all_auto_cancel_order($arr_field)->toarray();

        if (!empty($result)) {
            $res = '';
            foreach ($result as $value) {
                $up_data = [
                    'status' => 5,
                    'order_status' => 5,
                    'cancel_time' => date('Y-m-d H:i:s'),
                    'cancel_reason_id' => 0,
                    'cancel_reason' => '30分钟未支付自动取消'
                ];
                $res = StoreOrderRepository::edit_one((array)['id' => $value['id']], (array)$up_data);//取消订单

                StoreOrderRepository::cancelOrderBackStock((int)$value['id'], $value['user_coupons_id']);//回收库存

                //消息推送
                $dataNotice = [
                    'notice_type' => 'ptshp_order_message_push',
                    'order_id' => $value['id'],
                    'type' => 37,
                    'title' => '取消订单通知',
                    'content' => '30分钟内未支付已自动取消'
                ];
                predis_notice_queue_in($dataNotice);
            }
            if ($res) {
                return hello_success('取消成功');
            } else {
                return hello_error('取消失败');
            }
        }
        return hello_success('暂无可取消订单');
    }

    /**
     * 发货后十五天自动签收（和产品再三确认）
     * @return array
     */
    public function api_confirm_receipt()
    {
        //查询所有可关闭的订单
        $list = StoreOrderRepository::all_confirm_receipt();
        if (!empty($list)) {
            $orderIds = array_column($list, 'id');
            $up_data = ['status' => 3, 'order_status' => 3, 'receive_time' => date('Y-m-d H:i:s')];
            $res = StoreOrderRepository::update_by_where_in($orderIds, $up_data);
            if ($res) {
                return hello_success('关闭成功');
            } else {
                return hello_error('关闭失败');
            }
        }
        return hello_success('暂无可关闭订单');
    }

    /**
     * 收货十五天后关闭订单（和产品再三确认）
     * @return array
     */
    public function api_close_store_order()
    {
        //查询所有可关闭的订单
        $list = StoreOrderRepository::all_close_store_order();
        if (!empty($list)) {
            $orderIds = array_column($list, 'id');
            $res = StoreOrderRepository::update_by_where_in($orderIds, ['is_finish' => 1, 'status' => 20]);//关闭订单
            if ($res) {
                return hello_success('关闭成功');
            } else {
                return hello_error('关闭失败');
            }
        }
        return hello_success('暂无可关闭订单');
    }


    /**
     *  每分钟检测活动是否到期   ， 如果过期将当前活动下的商品重置为普通商品
     *    hinq 2020 04 15
     *
     **/
    public function api_activity_auto_cancel()
    {
        //获取所有的活动列表
        $arr_option['where'] = ['status' => 1];
        $arr_option['field'] = ['id', 'start_time', 'over_time', 'repairstore_id'];
        $arr_option['with'] = ['activity_goods_extend'];
        $arr_list = ActivityRepository::get_all((array)$arr_option)->toArray();
        if (!empty($arr_list)) {
            $str = '';
            $num = 0;
            foreach ($arr_list as $key => $vo) {
                // 活动的结束时间小于当前时间    获取已过期
                if ($vo['over_time'] < time()) {
                    $str .= $vo['id'] . ',';
                    $num++;
                    //将活动状态设置为已过期
                    ActivityRepository::change_one_state((int)$vo['id'], (int)4);
                    //将活动设置的商品设置为普通商品
                    $ids = '';
                    foreach ($vo['activity_goods_extend'] as $k => $v) {
                        $ids .= ',' . $v['goods'];
                    }
                    $ids = explode(',', trim($ids, ','));
                    if ($ids[0]) {
                        GoodsRepository::edit_whereIn((array)$ids, (array)['type' => 1]);
                    }
                    //删除购物车中的活动商品
                    \HiCommon\Repository\StoreCarRepository::delete_goods($ids);
                }
            }
            //添加日志
            $log_data['time'] = date("Y-m-d H:i:s");
            $log_data['num'] = $num;
            $log_data['activity_ids'] = trim($str, ',');
            $temp = 'ok, 成功修改' . $num . '条活动数据，【' . $log_data['activity_ids'] . '】';
            LogRepository::record_change_activity((array)$log_data);
            return hello_success($temp);
        }
    }


    /**
     *   每天凌晨检测是否有活动开始  如果有 将活动关联的商品设置为活动商品
     *    hinq 2020 05 27
     *
     **/
    public function api_activity_start_auto_cancel()
    {
        //获取所有的活动列表
        $arr_option['where'] = ['status' => 1, 'is_ac' => 0];
        $arr_option['field'] = ['id', 'start_time', 'over_time', 'repairstore_id'];
        $arr_option['with'] = ['activity_goods_extend'];
        $arr_list = ActivityRepository::get_all((array)$arr_option)->toArray();
        if (!empty($arr_list)) {
            $str = '';
            $num = 0;
            foreach ($arr_list as $key => $vo) {
                // 活动的开始时间小于当前时间   &&  当前时间小于活动的结束时间    活动进行中
                if ($vo['start_time'] <= time() && time() <= $vo['over_time']) {
                    $str .= $vo['id'] . ',';
                    $num++;
                    //将活动的类型设置为已经修改为普通商品
                    ActivityRepository::edit_one((array)['id' => $vo['id'], 'is_ac' => 1]);
                    //将活动关联的商品设置为活动商品
                    $ids = '';
                    foreach ($vo['activity_goods_extend'] as $k => $v) {
                        $ids .= ',' . $v['goods'];
                    }
                    $ids = explode(',', trim($ids, ','));
                    if ($ids[0]) {
                        GoodsRepository::edit_whereIn((array)$ids, (array)['type' => 3]);
                    }
                }
            }
            //添加日志
            $log_data['time'] = date("Y-m-d H:i:s");
            $log_data['num'] = $num;
            $log_data['activity_ids'] = trim($str, ',');
            $temp = 'ok, 成功修改' . $num . '条活动数据，【' . $log_data['activity_ids'] . '】';
            LogRepository::record_change_activity((array)$log_data);
            return hello_success($temp);
        }
    }


    /**
     *  每分钟道路救援订单是否到期   ，
     *    hinq 2020 04 15
     *
     **/
    public function api_road_rescue_auto_cancel()
    {
        //获取所有的活动列表
        $where = ['pay_status' => 2, 'status' => 0];
        $field = ['id', 'created_at', 'user_id', 'pid'];
        $arr_list = RoadRescueOrderRepository::get_all((array)$where, (array)$field);
        if (!empty($arr_list)) {
            $str = '';
            $num = 0;
            $arr_list = road_rescue_server_type();
            $service_pid_name = '';
            $service_pid_image = '';
            foreach ($arr_list as $key => $vo) {
                if (time() - $vo['created_at'] > 15 * 60) {
                    $str .= $vo['id'] . ',';
                    $num++;
                    $temp2['status'] = 4;
                    $temp2['id'] = $vo['id'];
                    RoadRescueOrderRepository::edit_one($temp2);

                    foreach ($arr_list as $key => $value) {
                        if ($value['id'] == $vo['pid']) {
                            $service_pid_name = $value['name'];
                            $service_pid_image = $value['image'];
                        }
                    }
                    $arr_jpush['extras']['pid'] = 3;
                    $arr_jpush['extras']['service_pid'] = $vo['pid'];
                    $arr_jpush['extras']['order_id'] = $vo['id'];

                    //添加系统消息
                    $temp['type'] = 37;   // 37：【订单消息】取消订单
                    $temp['order_status'] = 4;
                    $temp['service_pid'] = $vo['pid'];
                    $temp['shop_id'] = $vo['shop_id'];
                    $temp['order_type'] = 4;

                    add_message($service_pid_image, '取消订单', '您的道路救援订单【' . $service_pid_name . '】超时未支付，已自动取消', $vo['user_id'], 3
                        , $vo['id'], $arr_jpush, $temp);


                }
            }

        }
    }


    /**
     * 没分钟检测极光推送数据
     * @return array
     */
    public function api_jpush_activity()
    {
        //查询所有需要推送的订单
        $arr_option['field'] = ['id', 'activity_id', 'push_time', 'repairstore_id'];
        $arr_option['where'] = ['type' => 1];
        $arr_option['with'] = ['activity', 'shop'];
        $list = ActivityPushRepository::get_all((array)$arr_option)->toarray();
        $time = time();

        //获取平台所有用户
        $arr_option2['field'] = ['id'];
        $arr_option2['where'] = ['status' => 1];
        $arr_option2['with'] = ['user_jpush_by_activity'];
        $arr_user = \HiCommon\Repository\UsersRepository::get_all((array)$arr_option2)->toarray();

        //同已活动每天只能推送一次（计算需要缓存的时间）
        $day_last_time = strtotime(date('Y-m-d 23:59:59'));
        $mintes = $day_last_time - time();  //需要缓存的时间

        if (!empty($list)) {
            foreach ($list as $key => $vo) {
                if ($vo['push_time'] <= $time) {
                    $data['id'] = $vo['id'];
                    $data['type'] = 2;
                    ActivityPushRepository::edit_one((array)$data);   //修改当前数据为已推送状态

                    //极光推送需要的数据
                    $arr_jpush['platform'] = 'all';
                    $arr_jpush['title'] = '活动推送';
                    $arr_jpush['tag'] = 'PUSH';   //设备添加的标签
                    $arr_jpush['content'] = $vo['activity']['title'];
                    $arr_jpush['extras']['shop_id'] = $vo['shop']['id'];  // 扩展字段  店铺id
                    $arr_jpush['extras']['shop_name'] = empty($vo['shop']['name']) ? '' : $vo['shop']['name'];  // 扩展字段  店铺名称
                    $arr_jpush['extras']['shop_img'] = empty($vo['shop']['logo']) ? '' : oss_full_url($vo['shop']['logo']['full_src']);  // 扩展字段  店铺图像
                    $arr_jpush['extras']['pid'] = 2;   //消息类型  1：系统消息  2：活动消息  3：订单消息
                    $arr_jpush['type'] = 2;         //推送类型 1： 全平台用户   2：指定标签推送
                    $arr_jpush['ios_alert'] = $vo['activity']['title'];    //ios推送标题
                    JpushService::pushNotify((array)$arr_jpush);
                    \Cache::add('activity_' . $vo['activity_id'], 1, $mintes);  //添加活动推送缓存

                    //添加用户系统消息  不管用户是否设置接收推送消息  系统消息都给用户添加
                    foreach ($arr_user as $k => $v) {
                        //添加系统信息
                        $data_message['img'] = $vo['activity']['img']['full_src'];
                        $data_message['title'] = $vo['activity']['title'];
                        $data_message['pid'] = 2;
                        $data_message['type'] = 20;
                        $data_message['user_id'] = $v['id'];
                        $data_message['shop_id'] = $vo['activity']['repairstore_id'];
                        $data_message['shop_name'] = empty($vo['shop']['name']) ? '' : $vo['shop']['name'];
                        $data_message['activity_id'] = $vo['activity']['id'];
                        $data_message['is_read'] = 0;
                        $data_message['start_time'] = date('Y-m-d H:i:s', $vo['activity']['start_time']);
                        $data_message['over_time'] = date('Y-m-d H:i:s', $vo['activity']['over_time']);
                        $data_message['push_time'] = time_to_ymdhis();
                        $data_message['msg'] = $vo['activity']['title'];
                        \HiCommon\Repository\LogRepository::message_add((array)$data_message);
                    }
                }
            }
        }
        return hello_success('暂无推送信息');
    }


    /**
     *  检测用户未使用已过期的优惠券
     *  hinq 2020 5 13
     *
     **/
    public function api_coupons_auto_cancel()
    {

        //获取未使用并且即将要到期的优惠券(查找条件：过期时间小于当前时间戳 && 优惠券状态为未使用状态 )
        $arr_list = CouponGrantDetailRepository::get_timed_task_list()->toArray();
        if (!empty($arr_list)) {
            $ids = [];  //需要修改的数据集合
            foreach ($arr_list as $key => $value) {
                $ids[] = $value['id'];
            }
            //修改优惠券的状态 status = 3 已使用状态
            $res = CouponGrantDetailRepository::edit_timed_task_list((array)$ids);
            return hello_success('修改成功');
        }
        return hello_success('暂无优惠券修改');

    }

    /**
     *  检测是否有车辆需要检测 并推送
     *  hinq 2020 5 18
     *
     **/
    public function api_jpush_upkeep()
    {
        //获取所有的车辆信息
        $arr_whereIn = ['key'=>'is_push' , 'value'=> [0,1,2] ];   //获取未推送 和推送一次、二次的数据
        $arr_option['field'] = ['id', 'car_id', 'user_id', 'upkeep_time', 'is_push'];
        $arr_option['with'] = ['car_info' => function ($query) {
            $query->select('id', 'vehicle_model_id', 'users_company_id');
        }, 'car_info.simple_vehicle_model'];
        $arr_list = \HiCommon\Repository\UpKeepRepository::get_all_whereIn((array)$arr_option , (array) $arr_whereIn )->toarray();

        $time = date('Ymd'.'235959'  );  //当天时间
        if (!empty($arr_list)) {
            foreach ($arr_list as $key => $vo) {
                $day = 3;   //默认前三天前推送
                if( $vo['is_push'] == 1 ){   //推送次数
                    $day = 2;
                }else if( $vo['is_push'] == 2  ){
                    $day = 1;
                }
                $upkeep_time = date('Y-m-d' , $vo['upkeep_time'] - 3600 * 24 * $day );
                $next_upkeep_time =  date("YmdHis",strtotime("+6 months",  strtotime( $upkeep_time ) ) );
                if ( date('Ymd'.'000000' ) <= $next_upkeep_time && $next_upkeep_time < $time) {  // 下次推送的时间 == 今天
                    $is_push = $vo['is_push'] + 1;
                    if( $is_push > 3 ){  //最多只能推送3次
                        $is_push  = 3;
                    }
                    $arr_input2['id'] = $vo['id'];
                    $arr_input2['is_push'] = $is_push;
                    \HiCommon\Repository\UpKeepRepository::edit_one( (array) $arr_input2 );

                    $temp['type'] = 14;  //【系统消息】保养提醒
                    $temp['sys_type'] = 2;
                    $temp['car_id'] = $vo['car_id'];  //車輛id
                    $temp['name'] = $vo['car_info']['simple_vehicle_model']['name'];  //車輛名稱
                    $temp['one_name'] = $vo['car_info']['simple_vehicle_model']['one_name'];  //車輛名稱1
                    $temp['two_name'] = $vo['car_info']['simple_vehicle_model']['two_name'];  //車輛名稱2
                    $temp['three_name'] = $vo['car_info']['simple_vehicle_model']['three_name'];  //車輛名稱3
                    $temp['users_company_id'] = $vo['car_info']['users_company_id'];   //   企業id  0：個人車輛
                    $temp['over_time'] = date('Y-m-d', time() + 3600 * 24 * $day);  //   到期時間

                    $arr_jpush['extras']['pid'] = 1;
                    add_message($vo['car_info']['simple_vehicle_model']['logo'], '保养提醒', '您的车辆即将到达检车日，请于截止日之前完成检车', $vo['user_id'], 1, $vo['id'], $arr_jpush, $temp);
                }
            }
        }
        return hello_success('暂无推送信息');
    }


}